import logging
import random
from django_redis import get_redis_connection
from django.views import View
from django.http import JsonResponse
from celery_tasks.sms.tasks import ccp_send_sms_code


logger = logging.getLogger('django')


class SMSCodeView(View):
    def get(self, request, mobile):
        # redis建立连接
        redis_conn = get_redis_connection('verify_code')

        # 获取手机号发送标志位
        send_flag_mobile = redis_conn.get(f'send_flag_{mobile}')

        # 判断是否频繁发送验证码
        if send_flag_mobile:
            return JsonResponse({'success': False, 'message': '重复获取验证码'})

        # 随即生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # 创建redis管道
        rs_pl = redis_conn.pipeline()

        # 将redis请求加入到队列
        rs_pl.setex('sms_%s' % mobile, 300, sms_code)
        rs_pl.setex(f'send_flag_{mobile}', 60, '1')

        # 执行队列请求
        rs_pl.execute()

        # 生产环境
        ccp_send_sms_code.delay(mobile, sms_code)

        return JsonResponse({'success': True, 'sms_code': sms_code, 'message': 'ok'})
